<template>
  <div class='container'>
    <el-card class="box-card">
      <!-- 筛选区域 -->
      <!-- 按钮区域 -->
      <el-row>
        <el-col :span="12" style="color: red">
          说明:目前只支持学科和关键字条件筛选
        </el-col>
        <el-col :span="12">
          <el-button type="success" class="elBtn" @click="choiceAdd">
            <i class="el-icon-edit"></i> &nbsp;新增学科
          </el-button>
        </el-col>
      </el-row>
      <!-- 表单区域 -->
      <el-form ref="form" label-width="80px" :model="upForm">
        <!-- 第一行 -->
        <el-row>
          <el-col :span="6">
            <el-form-item label="学科">
              <el-select v-model="upForm.subjectValue" placeholder="请选择" @change='subject'>
                <el-option :label="item.label" v-for="item in upForm.subjectForm" :key="item.value" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="二级目录">
              <el-select placeholder="请选择" v-model="upForm.tagsValue">
                <el-option :label="item.label" v-for="item in upForm.tagsForm" :key="item.value" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标签">
              <el-select placeholder="请选择" v-model="upForm.twoLevelDirectoryValue">
                <el-option :label="item.label" v-for="item in upForm.twoLevelDirectoryForm" :key="item.value" :value='item.value'></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="关键字">
              <el-input v-model="upForm.keyword"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第二行 -->
        <el-row>
          <el-col :span="6">
            <el-form-item label="试题类型">
              <el-select placeholder="请选择" v-model="upForm.questionTypeValue">
                <el-option :label="item.label" :value="item.value" v-for="item in upForm.questionType" :key='item.value'></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="难度">
              <el-select placeholder="请选择" v-model="upForm.difficultyValue">
                <el-option :label="item.label" :value="item.value" v-for="item in upForm.difficulty" :key='item.value'></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="方向">
              <el-select placeholder="请选择" v-model="upForm.directionValue">
                <el-option :label="item" :value="item" v-for="item in upForm.direction" :key='item'></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="录入人">
              <el-select placeholder="请选择" v-model="upForm.creatorIDValue">
                <el-option :label="item.username" :value="item" v-for="item in upForm.creatorID" :key='item.id'></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第三行 -->
        <el-row>
          <el-col :span="6">
            <el-form-item label="题目备注">
              <el-input v-model="upForm.remarks"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="企业简称">
              <el-input v-model="upForm.shortName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="城市">
              <el-row>
                <el-col :span='12'>
                  <el-select placeholder="请选择" v-model="upForm.provincesValue" @change="provincesEvent">
                    <el-option :label="item" :value="item" v-for="item in upForm.provincesForm" :key="item.index"></el-option>
                  </el-select>
                </el-col>
                <el-col :span='12'>
                  <el-select placeholder="请选择" v-model="upForm.citysValue">
                    <el-option :label="item" :value="item" v-for="item in upForm.citysForm" :key="item.index"></el-option>
                  </el-select>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item style="float:right">
              <el-button @click="resetForm">清除</el-button>
              <el-button type="primary" @click="seachForm">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 列表区域 -->
      <!-- 选项卡 -->
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="全部" name="first"></el-tab-pane>
        <el-tab-pane label="待审核" name="second"></el-tab-pane>
        <el-tab-pane label="已审核" name="third"></el-tab-pane>
        <el-tab-pane label="已拒绝" name="fourth"></el-tab-pane>
      </el-tabs>
      <!-- 提示区域 -->
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple-light"><i class=" el-icon-warning"></i> &nbsp;数据一共{{downForm.counts}}条</div>
        </el-col>
      </el-row>
      <!-- 列表区域 -->
      <el-table :data="downForm.tableData" border style="width: 100%">
        <el-table-column prop="number" label="试题编号" width="150">
        </el-table-column>
        <el-table-column prop="subject" label="学科" width="120">
        </el-table-column>
        <el-table-column prop="catalog" label="目录" width="120">
        </el-table-column>
        <el-table-column prop="questionType" label="题型" width="120" :formatter='questionTypeRester'>
        </el-table-column>
        <el-table-column prop="question" label="题干" width="300">
          <template v-slot='{row}'>
            <p v-html="row.question"></p>
          </template>
        </el-table-column>
        <el-table-column prop="addDate" label="录入时间" width="120" :formatter='addDateRester'>
        </el-table-column>
        <el-table-column prop="difficulty" label="难度" width="120" :formatter='difficultyRester'>
        </el-table-column>
        <el-table-column prop="creator" label="录入人" width="120">
        </el-table-column>
        <el-table-column prop="chkState" label="审核状态" width="120" :formatter='chkStateRester'>
        </el-table-column>
        <el-table-column prop="chkRemarks" label="审核意见" width="120">
        </el-table-column>
        <el-table-column prop="chkUser" label="审核人" width="120">
        </el-table-column>
        <el-table-column prop="publishState" label="发布状态" width="120" :formatter='publishStateRester'>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
          <template v-slot={row}>
            <el-button type="text" size="small" @click="preview(row.id)">预览</el-button>
            <el-button type="text" size="small" :disabled='ifTrue(row)' @click="audit(row.id)">审核</el-button>
            <el-button type="text" size="small" :disabled='unTrue(row)' @click="modify(row.id)">修改</el-button>
            <el-button type="text" size="small" @click="shelves(row.publishState,row.id)">{{shelvesText(row.publishState )}}</el-button>
            <el-button type="text" size="small" :disabled='unTrue(row)' @click="del(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[1, 2, 3, 4]" :page-size.sync="pagesize" layout="sizes, prev, pager, next, jumper" :total="downForm.counts">
      </el-pagination>
    </el-card>
    <!-- 预览对话框 -->
    <QuestionsPreview :dialogVisible='dialogVisible' :handleClose='handleClose' :detailQuestions='detailQuestions' :videoBtn='videoBtn' :video='video' :questionTypeRester='questionTypeRester' :difficultyRester='difficultyRester' />
    <!-- 审核对话框 -->
    <el-dialog title="题目审核" width="20%" :visible.sync="dialogTableVisible">
      <el-radio v-model="auditRadio" :label="2" name="1">通过</el-radio>
      <el-radio v-model="auditRadio" :label="0" name="1">拒绝</el-radio>
      <el-input type="textarea" placeholder="请输入审核意见" v-model="text" maxlength="10" show-word-limit style="margin-top:36px"></el-input>
      <el-button @click="dialogTableVisible = false">取 消</el-button>
      <el-button type="primary" @click="auditEvent">确 认</el-button>
    </el-dialog>

  </div>
</template>

<script>
// 学科
import { simple as subjectsimple } from '@/api/hmmm/subjects.js'
import { simple as tagsSimple } from '@/api/hmmm/tags.js'
import { simple as directorysSimple } from '@/api/hmmm/directorys.js'
import { questionType, difficulty, direction, chkType, publishType } from '@/api/hmmm/constants.js'
import { simple as UsersSimple } from '@/api/base/users.js'
import { citys, provinces } from '@/api/hmmm/citys.js'
import { choice, detail, choicePublish, remove, choiceCheck } from '@/api/hmmm/questions.js'
import QuestionsPreview from '@/module-hmmm/components/questions-preview'
import dayjs from 'dayjs'
export default {
  name: 'QuestionsChoice',
  computed: {

  },
  data () {
    return {
      // 筛选区域表单数据
      upForm: {
        // 学科简单列表数据
        subjectForm: [],
        // 学科简单列表选中值
        subjectValue: '',
        // 学科二级目录列表数据
        twoLevelDirectoryForm: [],
        // 学科二级目录列表选中值
        twoLevelDirectoryValue: '',
        // 标签列表
        tagsForm: '',
        // 标签选中值
        tagsValue: '',
        // 试题类型
        questionTypeValue: '',
        questionType,
        // 困难
        difficultyValue: '',
        difficulty,
        // 方向
        directionValue: '',
        direction,
        // 录入人
        creatorIDValue: '',
        creatorID: '',
        // 所有城市
        provincesForm: '',
        provincesValue: '',
        // 所有城市下地区信息
        citysForm: '',
        citysValue: '',
        // 关键字
        keyword: '',
        // 题目备注
        remarks: '',
        // 企业简称
        shortName: ''
      },
      // 选项卡数据
      activeName: 'first',
      // 列表区域表单数据
      downForm: {
        // 列表区域表单总数据
        tableData: [],
        // 列表区域表单数据总记录数
        counts: 0,
        // 审核状态
        chkState: ''
        // 上架下架
        // publishState: ''
      },
      // 分页区域
      // 当前页
      currentPage: 1,
      // 每页几条数据
      pagesize: 1,
      // 预览对话框显示和隐藏
      dialogVisible: false,
      // 预览对话框显示信息
      detailQuestions: {
        questionType: '', // 题型
        number: 0, // 编号
        difficulty: '', // 难度
        tags: '', // 试题标签
        subjectID: '', // 学科
        directoryName: '', // 目录
        direction: '', // 方向
        question: '', // 题干
        // options: '', // 选项
        videoURL: '', // 解析视频
        answerID: '', // 答案解析
        remarks: ''// 题目备注
      },
      // 审核对话框显示信息
      dialogTableVisible: false,
      // 审核选项默认选中
      auditRadio: 0,
      // 审核选项输入框内容
      text: '',
      // 审核对话框id
      auditID: '',
      // 视频播放
      video: false
    }
  },
  components: {
    QuestionsPreview
  },
  created () {
    this.subjectSimple()
    this.handleClick()
    this.getProvinces()
  },
  methods: {
    // 新增学科
    choiceAdd () {
      console.log(this.$router)
      this.$router.push('/questions/new')
    },
    // 初始化时触发的事件,获取学科一级目录,录入人
    async subjectSimple () {
      const res = await subjectsimple()
      const ret = await UsersSimple()
      this.upForm.subjectForm = res.data
      this.upForm.creatorID = ret.data
    },
    // 一级目录下拉框选中值触发的事件
    async subject () {
      // 获取二级目录学科详情、标签(需要学科一级目录ID)
      this.upForm.twoLevelDirectoryValue = ''
      this.upForm.tagsValue = ''
      const res = await tagsSimple(
        { subjectID: this.upForm.subjectValue }
      )
      const ret = await directorysSimple({ subjectID: this.upForm.subjectValue })
      this.upForm.twoLevelDirectoryForm = res.data
      this.upForm.tagsForm = ret.data
    },
    // 清除筛选区域表单
    resetForm () {
      this.upForm = this.$options.data().upForm
      this.subjectSimple()
      this.getProvinces()
      this.handleClick()
    },
    // 根据筛选区域获取展示列表
    async seachForm () {
      this.pagesize = 100
      const oldObject = {
        page: this.currentPage,
        pagesize: this.pagesize,
        subjectID: this.upForm.subjectValue,
        difficulty: this.upForm.difficultyValue,
        questionType: this.upForm.questionTypeValue,
        tags: this.upForm.tagsValue,
        province: this.upForm.provinceValue,
        city: this.upForm.cityValue,
        keyword: this.upForm.keyword,
        remarks: this.upForm.remarks,
        shortName: this.upForm.shortName,
        direction: this.upForm.directionValue,
        creatorID: this.upForm.creatorIDValue,
        catalogID: this.upForm.twoLevelDirectoryValue
      }
      const newObject = {}
      for (const key in oldObject) {
        if (oldObject[key]) {
          newObject[key] = oldObject[key]
        }
      }
      const res = await choice(newObject)
      this.downForm.tableData = res.data.items
      this.downForm.counts = res.data.counts
      this.downForm.chkState = ''
    },
    // 获取所有城市信息（把导入到方法当作接口使用）
    getProvinces () {
      const res = provinces()
      this.upForm.provincesForm = res
    },
    // 获取所有城市下属地区信息
    provincesEvent () {
      this.upForm.citysValue = ''
      const res = citys(this.upForm.provincesValue)
      this.upForm.citysForm = res
      console.log(res)
    },
    // 列表区域数据格式化
    // 题型数据格式化
    questionTypeRester (val) {
      const res = questionType.find(item => {
        return item.value === Number(val.questionType)
      })
      return res ? res.label : '---'
    },
    // 对时间进行格式化
    addDateRester (val) {
      return dayjs(val.addDate).format('YYYY-MM-DD')
    },
    // 对难度进行格式化
    difficultyRester (val) {
      const res = difficulty.find(item => item.value === Number(val.difficulty))
      return res ? res.label : '---'
    },
    // 对审核状态进行格式化
    chkStateRester (val) {
      if (val.chkState === 0) {
        val.chkState = 3
      }
      const res = chkType.find(item => item.value === (val.chkState))
      return res ? res.label : '---'
    },
    // 对发布状态进行格式化
    publishStateRester (val) {
      console.log(val.chkState)
      const res = publishType.find(item => item.value === (val.chkState))
      console.log(res)
      return res ? res.label : '---'
    },
    // 选项卡方法
    // 选中选项卡时触发
    async handleClick () {
      // 确定审核状态(审核状态码貌似有问题)拒绝的状态码是0不是3
      if (this.activeName === 'second') this.downForm.chkState = '1'
      if (this.activeName === 'third') this.downForm.chkState = '2'
      if (this.activeName === 'fourth') this.downForm.chkState = '0'
      // 获取列表区域
      let res
      if (this.downForm.chkState) {
        res = await choice({
          chkState: this.downForm.chkState,
          page: this.currentPage,
          pagesize: this.pagesize
        })
        console.log(123)
        console.log(this.downForm.chkState)
      } else {
        res = await choice(
          {
            page: this.currentPage,
            pagesize: this.pagesize
          }
        )
        console.log(546)
      }
      this.downForm.tableData = res.data.items
      this.downForm.counts = res.data.counts
      this.downForm.chkState = ''
    },
    // 每页条数改变时触发
    handleSizeChange (page) {
      this.pagesize = page
      this.handleClick()
    },
    // 当前页条数改变时触发
    async handleCurrentChange (page) {
      this.currentPage = page
      this.handleClick()
    },
    // 操作预览
    async preview (id) {
      this.video = false
      this.dialogVisible = true
      const res = await detail({ id })
      console.log(res.data)
      this.detailQuestions = res.data
    },
    // 操作审核
    async audit (id) {
      this.dialogTableVisible = true
      const res = await detail({ id })
      this.auditRadio = res.data.chkState
      this.text = res.data.chkRemarks
      this.auditID = id
    },
    // 审核按钮的禁用
    ifTrue (row) {
      if (row.chkState !== 1) {
        return true
      } else {
        return false
      }
    },
    // 删除和修改按钮的禁用
    unTrue (row) {
      if (row.publishState === 0) {
        return false
      } else {
        return true
      }
    },
    // 操作修改
    modify (id) {
      this.$router.push('/questions/new?id=' + id)
    },
    // 操作上架
    shelves (publishState, id) {
      const res = this.shelvesText(publishState)
      this.$confirm(`此操作将${res}该试题, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let num
        if (publishState === 1) {
          num = 0
        } else {
          num = 1
        }
        const ret = await choicePublish({ id, publishState: num })
        if (ret.status === 200) {
          this.$message.success(`${res}成功`)
          this.handleClick()
        } else {
          this.$message.success(`未${res}成功`)
        }
      }).catch(() => {
        this.$message.success(`未${res}成功`)
      })
    },
    // 操作删除
    del (id) {
      this.$confirm('此操作将删除该试题, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const ret = await remove({ id })
        console.log(ret)
        if (ret.status === 200) {
          this.$message.success('删除成功')
          if (this.currentPage > 1 && this.pagesize === 1) {
            this.currentPage -= 1
          }
          this.handleClick()
        } else {
          this.$message.success('删除失败')
        }
      }).catch(() => {
        this.$message.success('删除失败')
      })
    },
    // 预览对话框
    handleClose () {
      this.dialogVisible = false
    },
    // 视频答案解析
    videoBtn () {
      this.video = true
    },
    // 确认审核
    async auditEvent () {
      try {
        await choiceCheck(
          {
            chkRemarks: this.text,
            chkState: this.auditRadio,
            id: this.auditID
          }
        )
        this.$message.success('已审核')
        this.dialogTableVisible = false
        this.handleClick()
      } catch (error) {

      }
    },
    // 操作上下架数据格式化
    shelvesText (shelves) {
      if (shelves === 0) return '上架'
      return '下架'
    }
  }
}
</script>

<style scoped lang='scss'>
.box-card {
  margin-left: 10px;
  margin-right: 10px;
  .elBtn {
    float: right;
    margin: 18px;
    margin-top: 0;
  }
  .bg-purple-light {
    background: #f4f4f5;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
    line-height: 36px;
    padding-left: 20px;
    margin-bottom: 20px;
    color: #909fc0;
    font-size: 14px;
  }
}
</style>
